/**
 * define all models
 */
import fs from 'fs'
import path from 'path'
import Sequelize from 'sequelize'
import mainconfig from '../config/db.js'

let config = mainconfig[process.env.NODE_ENV || 'development']

var sequelize = new Sequelize(config.database, config.username, config.password, config.detail)
var db = {}

fs.readdirSync(__dirname)
  .filter((file) => {
    return (file.indexOf('.') !== 0) && (file !== 'index.js') && (file.indexOf('.map') < 0)
  })
  .forEach((file) => {
    var model = sequelize.import(path.join(__dirname, file))
    db[model.name] = model
  })

Object.keys(db).forEach((modelName) => {
  if ('associate' in db[modelName]) {
    db[modelName].associate(db)
  }
})
db.sequelize = sequelize

module.exports = db
